<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Reality | Reality</title><meta name="keywords" content="Java, 全栈"><meta name="author" content="dtyy"><meta name="copyright" content="dtyy"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="1 Java中的基本数据类型Java中共有8种数据类型，分为三大类。 字符型：char 布尔型：boolean 数值型：1. 整型：byte、short、int、long；2. 浮点型：float、double String不是基本数据类型，是引用类型。 1.1 基本类型默认值0从表中可以看到起始默认值都是0，但是每个之间都有区别。例如，char默认值是单引号’\u0000’表示NUL（空的不可见">
<meta property="og:type" content="article">
<meta property="og:title" content="Reality">
<meta property="og:url" content="https://dtyytop.gitee.io/2021/05/13/devnotes/zhi-mian-java/ji-chu-pian/7-ji-ben-shu-ju-lei-xing-xiang-guan/index.html">
<meta property="og:site_name" content="Reality">
<meta property="og:description" content="1 Java中的基本数据类型Java中共有8种数据类型，分为三大类。 字符型：char 布尔型：boolean 数值型：1. 整型：byte、short、int、long；2. 浮点型：float、double String不是基本数据类型，是引用类型。 1.1 基本类型默认值0从表中可以看到起始默认值都是0，但是每个之间都有区别。例如，char默认值是单引号’\u0000’表示NUL（空的不可见">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222621.jpg">
<meta property="article:published_time" content="2021-05-13T14:22:22.268Z">
<meta property="article:modified_time" content="2021-05-27T14:46:24.132Z">
<meta property="article:author" content="dtyy">
<meta property="article:tag" content="Java, 全栈">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222621.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://dtyytop.gitee.io/2021/05/13/devnotes/zhi-mian-java/ji-chu-pian/7-ji-ben-shu-ju-lei-xing-xiang-guan/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"prismjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: true
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: dtyy","link":"链接: ","source":"来源: Reality","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Reality',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-05-27 22:46:24'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    })(window)</script><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="Reality" type="application/atom+xml">

<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">95</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">28</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">16</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/gallery/"><i class="fa-fw fas fa-images"></i><span> 图片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222621.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Reality</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/gallery/"><i class="fa-fw fas fa-images"></i><span> 图片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">无题</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-05-13T14:22:22.268Z" title="发表于 2021-05-13 22:22:22">2021-05-13</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-05-27T14:46:24.132Z" title="更新于 2021-05-27 22:46:24">2021-05-27</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1.7k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>6分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title=""><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="1-Java中的基本数据类型"><a href="#1-Java中的基本数据类型" class="headerlink" title="1 Java中的基本数据类型"></a><strong>1 Java中的基本数据类型</strong></h2><p>Java中共有8种数据类型，分为三大类。</p>
<p>字符型：char</p>
<p>布尔型：boolean</p>
<p>数值型：1. 整型：byte、short、int、long；2. 浮点型：float、double</p>
<p>String不是基本数据类型，是引用类型。</p>
<h3 id="1-1-基本类型默认值0"><a href="#1-1-基本类型默认值0" class="headerlink" title="1.1 基本类型默认值0"></a><strong>1.1 基本类型默认值0</strong></h3><p>从表中可以看到起始默认值都是0，但是每个之间都有区别。例如，char默认值是单引号’\u0000’表示NUL（空的不可见字符），其码值是0。</p>
<p>boolean类型的默认值是false，在JVM中仍然使用ICONST_0字节码指令赋值，即常数0。</p>
<pre class="line-numbers language-none"><code class="language-none">boolean b = false; 
1: iconst_0 
2: istore_1<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>



<h3 id="1-2-开发的时候注意数据溢出问题"><a href="#1-2-开发的时候注意数据溢出问题" class="headerlink" title="1.2 开发的时候注意数据溢出问题"></a><strong>1.2 开发的时候注意数据溢出问题</strong></h3><p>数据溢出的时候并不会报错，也没有任何提示。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">2147483647</span><span class="token punctuation">;</span> 
<span class="token keyword">int</span> j <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span> 
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>i <span class="token operator">+</span> j<span class="token punctuation">)</span><span class="token punctuation">;</span>  
运行结果：<span class="token operator">-</span><span class="token number">2147483648</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>因此需要开发人员在同类型数据运算时，注意数据溢出的问题，并避免编写容易导致溢出的代码。</p>
<pre class="line-numbers language-none"><code class="language-none">int mid = (i + j) / 2; 
替换为 
int mid = i + (j - i) / 2;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>



<h3 id="1-3-不同类型不能自动拆装箱"><a href="#1-3-不同类型不能自动拆装箱" class="headerlink" title="1.3 不同类型不能自动拆装箱"></a><strong>1.3 不同类型不能自动拆装箱</strong></h3><pre class="line-numbers language-none"><code class="language-none">int i = 0; 
Long j = i;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>int类型的包装类是Integer，无法转化成Long类型。</p>
<h3 id="1-4-MySQL-int的取值范围（先记在这，哈哈）"><a href="#1-4-MySQL-int的取值范围（先记在这，哈哈）" class="headerlink" title="1.4 MySQL int的取值范围（先记在这，哈哈）"></a><strong>1.4 MySQL int的取值范围（先记在这，哈哈）</strong></h3><p>记得有这样一道面试题：如果采用自增int作为主键，主键不够用怎么办。很多小伙伴可能会答换成更大的类型long。无符号int类型作为主键，有着很大的取值范围，如果表的记录无需到达int取值上限，就需要考虑分表了。</p>
<h2 id="2-浮点类型"><a href="#2-浮点类型" class="headerlink" title="2 浮点类型"></a><strong>2 浮点类型</strong></h2><h3 id="2-1-原码、反码、补码、移码"><a href="#2-1-原码、反码、补码、移码" class="headerlink" title="2.1 原码、反码、补码、移码"></a><strong>2.1 原码、反码、补码、移码</strong></h3><p>对于正数，原码、反码、补码相同，均为正数本身。</p>
<p>对于负数：原码的符号位是1。反码符号位为1，其他位为原码取反。补码为反码末尾加1。</p>
<pre class="line-numbers language-none"><code class="language-none">原码：1111 1111（-127） 
反码：1000 0000 
补码：1000 0001 
原码：1000 0000（二进制 -128，也是-0） 
反码：1111 1111 
补码：-(111 1111 + 1) = -128<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>原码的出现是为了引入负数。</p>
<pre class="line-numbers language-none"><code class="language-none">原码：1111 1111 ~ 0111 1111 
真值范围：-127 ~127（255个） 
其中1000 0000和0000 0000都表示0<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>原码存在带符号位运算的问题。</p>
<pre class="line-numbers language-none"><code class="language-none">-1:1000 0001(原码) 
+1:0000 0001(原码) 
加和:1000 0010(原码) = -2是不正确的<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>反码的定义：如果是正数则保持不变，如果是负数，则除符号位之外按位取反。</p>
<pre class="line-numbers language-none"><code class="language-none">-1:1111 1110(反码) 
+1:0000 0001(反码) 
加和:1111 1111(反码) = 1000 0000(原码) = -0 = 0<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>补码的出现用于解决+0和-0的问题。补码的定义就是正数和 0 的补码不变，负数的补码是其对应的正数按位取反再 +1。有了补码，8进制就可以用1000 0000表示-128，此时8进制可以表示256个数。</p>
<pre class="line-numbers language-none"><code class="language-none">-1:1111 1111(补码) 
+1:0000 0001(补码) 
加和:(1)0000 0000(补码) = 0000 0000(原码) = 0<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>移码是将符号位取反的补码。</p>
<p>对于按位与操作，非常典型的场景是用于获取当前IP网段，即IP地址与掩码255.255.255.0进行按位与运算得到高24位。</p>
<h3 id="2-2-浮点数的表示"><a href="#2-2-浮点数的表示" class="headerlink" title="2.2 浮点数的表示"></a><strong>2.2 浮点数的表示</strong></h3><p>计算机内部采用二进制表示，浮点数是对实数的近似数值表示，其采用科学计数法来表示，由符号位、指数和有效数字三部分组成。</p>
<p>以单精度浮点数为例，占4个字节32位，32位包含1个符号位、8个指数位和23个有效数字。有效数字位是小数点后二进制表示。</p>
<p><img src="F:\笔记数据\有道云笔记\qqA1EC571BD6B11E135ADBF355C9DFA974\844e86c1d4634517a5588b6d65bbfe0f\clipboard.png" alt="img"></p>
<p>符号位：0表示正数，1表示负数。</p>
<p>指数位：存储指数对应的移码。将[-128, 127]平移成正数域，IEEE标准规定指数范围是[-126, 127]。指数位仅用于表示科学计数法指数大小。</p>
<p>尾数位：以原码表示。正数为1，尾数形式为1.xyz，xyz即有效数字。</p>
<pre class="line-numbers language-none"><code class="language-none">例1:16.35 
0100-0001-1000-0010-1100-1100-1101 
0：表示正数 
100-0001-1：131-127=4，表示指数是2^4=16 
000-0010-1100-1100-1101：尾数0.35 

例2:0.35 
0011-1110-1011-0011-0011-0011-0011 
0：表示正数 
011-1110-1：127-127=0，表示2的0次方 
011-0011-0011-0011-0011：尾数位<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>同样是0.35,为何尾数位不同？</p>
<pre class="line-numbers language-none"><code class="language-none">0.35(十进制) = 0.0101100110011001(二进制) 
16.35(十进制)= 1.0000010110011001(二进制)<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>例2中尾数位是正确的，而对于例1中16.35,16的二进制为10000，转换为小数点前1的规格化是1.0000 * 2^4，占用了4个有效数字位。</p>
<h3 id="2-3-浮点数计算不准确，精确计算用定点数"><a href="#2-3-浮点数计算不准确，精确计算用定点数" class="headerlink" title="2.3 浮点数计算不准确，精确计算用定点数"></a><strong>2.3 浮点数计算不准确，精确计算用定点数</strong></h3><p>如上分析，使用浮点数是不一定能表示正确的数值，正如1-0.9结果不是0.1。在实际开发过程中，对精度要求高的运算过程都是采用定点数表示，并且是使用BigDecimal类String参数构造器！！</p>
<pre class="line-numbers language-JAVA" data-language="JAVA"><code class="language-JAVA">public class BigDecimalTest {
    @Test
    public void test1(){
        System.out.println(0.05 + 0.01);
    }
    @Test
    public void test2(){
        BigDecimal b1 = new BigDecimal(0.05);
        BigDecimal b2 = new BigDecimal(0.01);
        System.out.println(b1.add(b2));
    }
    @Test
    public void test3(){
        BigDecimal b1 = new BigDecimal("0.05");
        BigDecimal b2 = new BigDecimal("0.01");
        System.out.println(b1.add(b2));
    }
}
运行结果：
0.060000000000000005
0.06000000000000000298372437868010820238851010799407958984375
0.06<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="3-随机数与类型转换"><a href="#3-随机数与类型转换" class="headerlink" title="3 随机数与类型转换"></a><strong>3 随机数与类型转换</strong></h2><h3 id="3-1-生成随机数的方法"><a href="#3-1-生成随机数的方法" class="headerlink" title="3.1 生成随机数的方法"></a><strong>3.1 生成随机数的方法</strong></h3><p>返回[0, 10)中的随机整数 </p>
<pre class="line-numbers language-none"><code class="language-none">1. (int)(Math.random() * 10) 
2. 利用Random工具类 
Random rand = new Random(); 
rand.nextInt(10);<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>虽然Random工具类很强大，大多时候开发中我会采用第一种方法，不需要生成新的对象。</p>
<h3 id="3-2-快速计算负数的四舍五入"><a href="#3-2-快速计算负数的四舍五入" class="headerlink" title="3.2 快速计算负数的四舍五入"></a>3.2 <strong>快速计算负数的四舍五入</strong></h3><p>我们在计算负数的四舍五入的时候，通常会有所迟疑。</p>
<pre class="line-numbers language-none"><code class="language-none">Math.round(a) == (int)Math.floor(a + 0.5)<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>因此，四舍五入等于当前数值加上0.5，再向下取整。方法适用于正负数，哈哈。</p>
<h3 id="3-3-类型提升"><a href="#3-3-类型提升" class="headerlink" title="3.3 类型提升"></a><strong>3.3 类型提升</strong></h3><p>（1）将比较小的类型（char/byte/short)传递给Integer.toBinaryString()方法，则该类型会自动转换为int。</p>
<p>（2）基本数据类型执行算数计算或按位运算时，只要类型比int小（char、byte、short类型），运算之前会总动转为int类型，得到的结果也是int类型。如果往回赋值，截断。例如，short类型-1在无符号右移10位，值仍为-1。</p>
<p>案例1：按位运算</p>
<pre class="line-numbers language-none"><code class="language-none">short s = -1;
s = s &gt;&gt;&gt; 10;
过程：

原二进制表示： 
1111 1111 1111 1111

先转换为32位int类型
1111 1111 1111 1111 1111 1111 1111 1111

进行移位操作
0000 0000 0011 1111 1111 1111 1111 1111

赋值给s，截断
1111 1111 1111 1111<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>案例2：算术运算</p>
<pre class="line-numbers language-none"><code class="language-none">short x = 1; 
short y = 2; 
x = (short)(x * y); 
x *= y;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>复合赋值不需要强制类型转换。</p>
<p><strong>3.4 除了布尔值外，其他基本数据类型可以相互转换。</strong></p>
<p><strong>问：Java中的char是否可以存储中文字符？</strong></p>
<p>解：Java中的char存储占2个字节。中文使用unicode编码，同样占两个字节。只要在unicode编码中有的中文，即可以用char存储。除了一下生僻字和特殊字之外。</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">dtyy</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://dtyytop.gitee.io/2021/05/13/devnotes/zhi-mian-java/ji-chu-pian/7-ji-ben-shu-ju-lei-xing-xiang-guan/">https://dtyytop.gitee.io/2021/05/13/devnotes/zhi-mian-java/ji-chu-pian/7-ji-ben-shu-ju-lei-xing-xiang-guan/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://dtyytop.gitee.io" target="_blank">Reality</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222621.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://gitee.com/dtyytop/blogimage/raw/master/img/20210515001034.png" target="_blank"><img class="post-qr-code-img" src="https://gitee.com/dtyytop/blogimage/raw/master/img/20210515001034.png" alt="wechat"/></a><div class="post-qr-code-desc">wechat</div></li><li class="reward-item"><a href="https://gitee.com/dtyytop/blogimage/raw/master/img/20210515001009.png" target="_blank"><img class="post-qr-code-img" src="https://gitee.com/dtyytop/blogimage/raw/master/img/20210515001009.png" alt="alipay"/></a><div class="post-qr-code-desc">alipay</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2021/05/13/devnotes/zhi-mian-java/ji-chu-pian/4-java-de-ping-tai-wu-guan-xing/"><img class="prev-cover" src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222554.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info"></div></div></a></div><div class="next-post pull-right"><a href="/2021/05/13/devnotes/zhi-mian-java/bing-fa/kuai-wen-kuai-da/kuai-wen-kuai-da/"><img class="next-cover" src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222627.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info"></div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">dtyy</div><div class="author-info__description">Java全栈</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">95</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">28</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">16</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/dtyytop"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/dtyytop" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:1607961042@qq.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-Java%E4%B8%AD%E7%9A%84%E5%9F%BA%E6%9C%AC%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B"><span class="toc-number">1.</span> <span class="toc-text">1 Java中的基本数据类型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-%E5%9F%BA%E6%9C%AC%E7%B1%BB%E5%9E%8B%E9%BB%98%E8%AE%A4%E5%80%BC0"><span class="toc-number">1.1.</span> <span class="toc-text">1.1 基本类型默认值0</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-%E5%BC%80%E5%8F%91%E7%9A%84%E6%97%B6%E5%80%99%E6%B3%A8%E6%84%8F%E6%95%B0%E6%8D%AE%E6%BA%A2%E5%87%BA%E9%97%AE%E9%A2%98"><span class="toc-number">1.2.</span> <span class="toc-text">1.2 开发的时候注意数据溢出问题</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-3-%E4%B8%8D%E5%90%8C%E7%B1%BB%E5%9E%8B%E4%B8%8D%E8%83%BD%E8%87%AA%E5%8A%A8%E6%8B%86%E8%A3%85%E7%AE%B1"><span class="toc-number">1.3.</span> <span class="toc-text">1.3 不同类型不能自动拆装箱</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-4-MySQL-int%E7%9A%84%E5%8F%96%E5%80%BC%E8%8C%83%E5%9B%B4%EF%BC%88%E5%85%88%E8%AE%B0%E5%9C%A8%E8%BF%99%EF%BC%8C%E5%93%88%E5%93%88%EF%BC%89"><span class="toc-number">1.4.</span> <span class="toc-text">1.4 MySQL int的取值范围（先记在这，哈哈）</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-%E6%B5%AE%E7%82%B9%E7%B1%BB%E5%9E%8B"><span class="toc-number">2.</span> <span class="toc-text">2 浮点类型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1-%E5%8E%9F%E7%A0%81%E3%80%81%E5%8F%8D%E7%A0%81%E3%80%81%E8%A1%A5%E7%A0%81%E3%80%81%E7%A7%BB%E7%A0%81"><span class="toc-number">2.1.</span> <span class="toc-text">2.1 原码、反码、补码、移码</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-%E6%B5%AE%E7%82%B9%E6%95%B0%E7%9A%84%E8%A1%A8%E7%A4%BA"><span class="toc-number">2.2.</span> <span class="toc-text">2.2 浮点数的表示</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3-%E6%B5%AE%E7%82%B9%E6%95%B0%E8%AE%A1%E7%AE%97%E4%B8%8D%E5%87%86%E7%A1%AE%EF%BC%8C%E7%B2%BE%E7%A1%AE%E8%AE%A1%E7%AE%97%E7%94%A8%E5%AE%9A%E7%82%B9%E6%95%B0"><span class="toc-number">2.3.</span> <span class="toc-text">2.3 浮点数计算不准确，精确计算用定点数</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-%E9%9A%8F%E6%9C%BA%E6%95%B0%E4%B8%8E%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2"><span class="toc-number">3.</span> <span class="toc-text">3 随机数与类型转换</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#3-1-%E7%94%9F%E6%88%90%E9%9A%8F%E6%9C%BA%E6%95%B0%E7%9A%84%E6%96%B9%E6%B3%95"><span class="toc-number">3.1.</span> <span class="toc-text">3.1 生成随机数的方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-2-%E5%BF%AB%E9%80%9F%E8%AE%A1%E7%AE%97%E8%B4%9F%E6%95%B0%E7%9A%84%E5%9B%9B%E8%88%8D%E4%BA%94%E5%85%A5"><span class="toc-number">3.2.</span> <span class="toc-text">3.2 快速计算负数的四舍五入</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-3-%E7%B1%BB%E5%9E%8B%E6%8F%90%E5%8D%87"><span class="toc-number">3.3.</span> <span class="toc-text">3.3 类型提升</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/06/02/devnotes/ji-qun-yan-jin/nginx/1.3-nginx-jin-cheng-mo-xing-yu-shi-jian-chu-li-ji-zhi/" title="Nginx进程模型"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222600.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Nginx进程模型"/></a><div class="content"><a class="title" href="/2021/06/02/devnotes/ji-qun-yan-jin/nginx/1.3-nginx-jin-cheng-mo-xing-yu-shi-jian-chu-li-ji-zhi/" title="Nginx进程模型">Nginx进程模型</a><time datetime="2021-06-01T16:00:00.000Z" title="发表于 2021-06-02 00:00:00">2021-06-02</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/06/02/devnotes/ji-qun-yan-jin/nginx/1.4-nginx-he-xin-wen-jian-jie-gou-fen-xi/" title="Nginx核心配置结构"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222629.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Nginx核心配置结构"/></a><div class="content"><a class="title" href="/2021/06/02/devnotes/ji-qun-yan-jin/nginx/1.4-nginx-he-xin-wen-jian-jie-gou-fen-xi/" title="Nginx核心配置结构">Nginx核心配置结构</a><time datetime="2021-06-01T16:00:00.000Z" title="发表于 2021-06-02 00:00:00">2021-06-02</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/05/30/devnotes/ji-qun-yan-jin/nginx/1.2-wei-shi-me-xuan-ze-nginx/" title="集群、代理与Nginx"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222629.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="集群、代理与Nginx"/></a><div class="content"><a class="title" href="/2021/05/30/devnotes/ji-qun-yan-jin/nginx/1.2-wei-shi-me-xuan-ze-nginx/" title="集群、代理与Nginx">集群、代理与Nginx</a><time datetime="2021-05-29T16:00:00.000Z" title="发表于 2021-05-30 00:00:00">2021-05-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/05/30/devnotes/ji-qun-yan-jin/redis/redis-zhu-cong-fu-zhi-yu-yuan-li/" title="Redis主从复制架构与原理"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222646.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Redis主从复制架构与原理"/></a><div class="content"><a class="title" href="/2021/05/30/devnotes/ji-qun-yan-jin/redis/redis-zhu-cong-fu-zhi-yu-yuan-li/" title="Redis主从复制架构与原理">Redis主从复制架构与原理</a><time datetime="2021-05-29T16:00:00.000Z" title="发表于 2021-05-30 00:00:00">2021-05-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/05/30/devnotes/ji-qun-yan-jin/redis/redis-chi-jiu-hua-ji-zhi/" title="Redis的两种持久化机制"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222634.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Redis的两种持久化机制"/></a><div class="content"><a class="title" href="/2021/05/30/devnotes/ji-qun-yan-jin/redis/redis-chi-jiu-hua-ji-zhi/" title="Redis的两种持久化机制">Redis的两种持久化机制</a><time datetime="2021-05-29T16:00:00.000Z" title="发表于 2021-05-30 00:00:00">2021-05-30</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222621.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By dtyy</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"></div><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="false"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>